<template>
  <div class="order-list-page">
    <div class="order-container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h2>我的订单</h2>
      </div>

      <!-- 订单状态筛选 -->
      <div class="order-tabs">
        <el-tabs v-model="activeStatus" @tab-change="handleStatusChange">
          <el-tab-pane :name="null" label="全部"/>
          <el-tab-pane :name="1" label="待支付"/>
          <el-tab-pane :name="2" label="待发货"/>
          <el-tab-pane :name="3" label="待收货"/>
          <el-tab-pane :name="4" label="已完成"/>
          <el-tab-pane :name="5" label="已取消"/>
        </el-tabs>
      </div>

      <!-- 订单列表 -->
      <div v-loading="loading" class="order-list">
        <div v-if="orders.length > 0" class="orders">
          <div
              v-for="order in orders"
              :key="order.id"
              class="order-item"
          >
            <!-- 订单头部 -->
            <div class="order-header">
              <div class="order-info">
                <span class="order-number">订单号：{{ order.orderNo }}</span>
                <span class="order-time">下单时间：{{ formatDateTime(order.createTime) }}</span>
                <span v-if="order.payTime" class="pay-time">支付时间：{{ formatDateTime(order.payTime) }}</span>
                <span v-if="order.deliveryTime" class="delivery-time">发货时间：{{
                    formatDateTime(order.deliveryTime)
                  }}</span>
                <span v-if="order.receiveTime" class="receive-time">收货时间：{{
                    formatDateTime(order.receiveTime)
                  }}</span>
              </div>
              <div class="order-status">
                <el-tag :type="getStatusType(order.status)">
                  {{ getStatusText(order.status) }}
                </el-tag>
              </div>
            </div>

            <!-- 订单商品 -->
            <div class="order-products">
              <div
                  v-for="item in order.orderItems"
                  :key="item.id"
                  class="product-item"
                  @click="goToProductDetail(item.productId)"
              >
                <div class="product-image">
                  <el-image
                      :alt="item.productName"
                      :src="item.productImage || '/placeholder.jpg'"
                      fit="cover"
                  />
                </div>
                <div class="product-info">
                  <h4 class="product-name">{{ item.productName }}</h4>
                  <div class="product-price">单价：¥{{ formatPrice(item.unitPrice) }}</div>
                  <div class="product-subtotal">
                    小计：¥{{ formatPrice(item.totalPrice || (item.unitPrice * item.quantity)) }}
                  </div>
                </div>
                <div class="product-quantity">
                  数量：{{ item.quantity }}
                </div>
              </div>
            </div>

            <!-- 订单金额 -->
            <div class="order-amount">
              <div class="amount-details">
                <span>共{{ order.itemCount || order.orderItems?.length || 0 }}件商品</span>
                <span v-if="order.discountAmount && order.discountAmount > 0">
                  优惠金额：-¥{{ formatPrice(order.discountAmount) }}
                </span>
                <span v-if="order.shippingFee && order.shippingFee > 0">
                  运费：¥{{ formatPrice(order.shippingFee) }}
                </span>
              </div>
              <span class="total-amount">实付金额：¥{{ formatPrice(order.totalAmount) }}</span>
            </div>

            <!-- 订单操作 -->
            <div class="order-actions">
              <el-button size="small" @click="viewOrderDetail(order.id)">
                查看详情
              </el-button>

              <el-button
                  v-if="order.status === 1"
                  size="small"
                  type="primary"
                  @click="payOrder(order.id)"
              >
                立即支付
              </el-button>

              <el-button
                  v-if="order.status === 1"
                  size="small"
                  @click="cancelOrder(order.id)"
              >
                取消订单
              </el-button>

              <el-button
                  v-if="order.status === 3"
                  size="small"
                  type="success"
                  @click="confirmOrder(order.id)"
              >
                确认收货
              </el-button>

              <el-button
                  v-if="order.status === 4 && !order.hasCommented"
                  size="small"
                  @click="commentOrder(order.id)"
              >
                评价商品
              </el-button>
              <span
                  v-if="order.status === 4 && order.hasCommented"
                  class="commented-text"
              >
                已评价
              </span>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else-if="!loading" class="empty-orders">
          <el-empty description="暂无订单">
            <el-button type="primary" @click="goToHome">去购物</el-button>
          </el-empty>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="total > 0" class="pagination">
        <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            background
            layout="prev, pager, next, jumper"
            @current-change="handlePageChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage, ElMessageBox} from 'element-plus'
import {cancelOrder as cancelOrderApi, confirmOrder as confirmOrderApi, getUserOrders} from '@/api/order'
import {getOrderItemsCommentStatus} from '@/api/comment'
import {formatDateTime} from '@/utils'

// 路由相关
const router = useRouter()

// 响应式数据
const loading = ref(false)
const activeStatus = ref(null)
const orders = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 页面初始化
onMounted(() => {
  fetchOrders()
})


// 获取订单列表
const fetchOrders = async () => {
  try {
    loading.value = true

    const params = {
      current: currentPage.value,
      size: pageSize.value,
      status: activeStatus.value
    }

    const response = await getUserOrders(params)
    const orderList = response.data?.records || []

    // 为已完成的订单检查评论状态
    for (const order of orderList) {
      if (order.status === 4) {
        try {
          // 获取订单中商品的评论状态
          const response = await getOrderItemsCommentStatus(order.id)
          const commentStatusMap = response.data || {}

          // 检查是否所有商品都已评论
          // 只有当所有商品都已评论时，才认为订单已评论
          const productIds = order.orderItems?.map(item => item.productId) || []
          const allCommented = productIds.length > 0 && productIds.every(productId => commentStatusMap[productId] === true)

          order.hasCommented = allCommented
        } catch (error) {
          console.error('检查评论状态失败:', error)
          order.hasCommented = false
        }
      } else {
        order.hasCommented = false
      }
    }

    orders.value = orderList
    total.value = response.data?.total || 0
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 状态筛选变化
const handleStatusChange = (status) => {
  activeStatus.value = status
  currentPage.value = 1
  fetchOrders()
}

// 分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  fetchOrders()
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    1: 'warning',  // 待支付
    2: 'info',     // 待发货
    3: 'primary',  // 待收货
    4: 'success',  // 已完成
    5: 'danger'    // 已取消
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    1: '待支付',
    2: '待发货',
    3: '待收货',
    4: '已完成',
    5: '已取消'
  }
  return statusMap[status] || '未知状态'
}

// 查看订单详情
const viewOrderDetail = (orderId) => {
  router.push(`/order/${orderId}`)
}

// 支付订单 - 跳转到支付页面
const payOrder = (orderId) => {
  // 找到对应的订单信息
  const order = orders.value.find(o => o.id === orderId)
  if (!order) {
    ElMessage.error('订单信息不存在')
    return
  }

  // 跳转到支付页面
  router.push({
    path: `/payment/${orderId}`,
    query: {
      orderNo: order.orderNo,
      totalAmount: order.totalAmount
    }
  })
}

// 取消订单
const cancelOrder = async (orderId) => {
  try {
    await ElMessageBox.confirm('确定要取消这个订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await cancelOrderApi(orderId, '用户取消订单')
    ElMessage.success('订单已取消')
    await fetchOrders()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  }
}

// 确认收货
const confirmOrder = async (orderId) => {
  try {
    await ElMessageBox.confirm('确定已收到商品吗？', '确认收货', {
      confirmButtonText: '确认收货',
      cancelButtonText: '取消',
      type: 'info'
    })

    await confirmOrderApi(orderId)
    ElMessage.success('确认收货成功')
    await fetchOrders()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认收货失败:', error)
      ElMessage.error('确认收货失败')
    }
  }
}

// 评价商品
const commentOrder = (orderId) => {
  // 跳转到评价选择页面
  router.push(`/order/${orderId}/select`)
}

// 跳转到商品详情
const goToProductDetail = (productId) => {
  router.push(`/product/${productId}`)
}

// 跳转到首页
const goToHome = () => {
  router.push('/home')
}

// 格式化价格
const formatPrice = (price) => {
  if (price === null || price === undefined || isNaN(price)) {
    return '0.00'
  }
  return parseFloat(price).toFixed(2)
}
</script>

<style scoped>
.order-list-page {
  min-height: 100vh;
  background: var(--bg-secondary);
  padding: 2rem 0;
}

.order-container {
  max-width: 1200px;
  margin: 0 auto;
  background: var(--bg-card);
  border-radius: var(--radius-2xl);
  overflow: hidden;
  box-shadow: var(--shadow-lg);
  border: 1px solid var(--border-light);
}

.page-header {
  padding: 1.5rem 2rem;
  border-bottom: 1px solid var(--border-light);
  background: var(--bg-secondary);
}

.page-header h2 {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 700;
  color: var(--text-primary);
}

.order-tabs {
  padding: 0 2rem;
  background: var(--bg-card);
  border-bottom: 1px solid var(--border-light);
}

.order-list {
  padding: 2rem;
  min-height: 400px;
}

.order-item {
  border: 1px solid var(--border-light);
  border-radius: var(--radius-2xl);
  margin-bottom: 1.5rem;
  background: var(--bg-card);
  overflow: hidden;
  box-shadow: var(--shadow-sm);
  transition: all 0.3s ease;
}

.order-item:hover {
  box-shadow: var(--shadow-md);
  transform: translateY(-2px);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #ebeef5;
}

.order-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.order-number {
  font-weight: 600;
  color: #303133;
}

.order-time,
.pay-time,
.delivery-time,
.receive-time {
  color: #909399;
  font-size: 14px;
}

.order-products {
  padding: 20px;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
  cursor: pointer;
  transition: background-color 0.3s;
}

.product-item:hover {
  background-color: #f8f9fa;
}

.product-item:not(:last-child) {
  border-bottom: 1px solid #f0f0f0;
}

.product-image {
  width: 80px;
  height: 80px;
  margin-right: 15px;
}

.product-image .el-image {
  width: 100%;
  height: 100%;
  border-radius: 4px;
}

.product-info {
  flex: 1;
  margin-right: 15px;
}

.product-name {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #303133;
  line-height: 1.4;
}

.product-price,
.product-subtotal {
  color: #f56c6c;
  font-weight: 600;
  font-size: 14px;
  margin-top: 4px;
}

.product-quantity {
  color: #606266;
  margin-right: 20px;
}

.order-amount {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #f8f9fa;
  border-top: 1px solid #ebeef5;
  color: #606266;
}

.amount-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
  color: #909399;
  font-size: 14px;
}

.total-amount {
  font-size: 16px;
  font-weight: 600;
  color: #f56c6c;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
}

.pagination {
  display: flex;
  justify-content: center;
  padding: 30px;
  background: white;
  border-top: 1px solid #ebeef5;
}

/* 响应式设计 */
/* 平板端 */
@media (max-width: 1024px) {
  .order-container {
    margin: 0 15px;
  }

  .order-info {
    gap: 15px;
  }

  .product-item {
    padding: 12px 0;
  }
}

/* 移动端 */
@media (max-width: 768px) {
  .order-list-page {
    padding: 1rem 0;
  }

  .order-container {
    margin: 0 1rem;
  }

  .page-header {
    padding: 1rem 1.5rem;
  }

  .page-header h2 {
    font-size: 1.25rem;
  }

  .order-tabs {
    padding: 0 1.5rem;
  }

  .order-list {
    padding: 1.5rem;
  }

  .page-header {
    padding: 12px 15px;
  }

  .page-header h2 {
    font-size: 18px;
  }

  .order-tabs {
    padding: 0 15px;
  }

  .order-card {
    margin-bottom: 15px;
    border-radius: 8px;
  }

  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
    padding: 12px 15px;
  }

  .order-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
    width: 100%;
  }

  .order-number {
    font-size: 14px;
  }

  .order-time,
  .pay-time,
  .delivery-time,
  .receive-time {
    font-size: 12px;
  }

  .order-products {
    padding: 15px;
  }

  .product-item {
    flex-direction: row;
    align-items: center;
    gap: 12px;
    padding: 10px 0;
  }

  .product-image {
    width: 60px;
    height: 60px;
    flex-shrink: 0;
  }

  .product-info {
    flex: 1;
    min-width: 0;
  }

  .product-name {
    font-size: 13px;
    line-height: 1.3;
    margin-bottom: 4px;
  }

  .product-price {
    font-size: 14px;
  }

  .order-footer {
    padding: 12px 15px;
  }

  .order-actions {
    flex-wrap: wrap;
    justify-content: center;
    gap: 8px;
  }

  .order-actions .el-button {
    font-size: 12px;
    padding: 6px 12px;
  }

  .pagination {
    padding: 15px;
  }
}

/* 小屏手机 */
@media (max-width: 480px) {
  .order-container {
    margin: 0 8px;
  }

  .order-list {
    padding: 10px;
  }

  .page-header {
    padding: 10px 12px;
  }

  .page-header h2 {
    font-size: 16px;
  }

  .order-tabs {
    padding: 0 12px;
  }

  .order-card {
    margin-bottom: 12px;
  }

  .order-header {
    padding: 10px 12px;
  }

  .order-products {
    padding: 12px;
  }

  .product-item {
    gap: 10px;
    padding: 8px 0;
  }

  .product-image {
    width: 50px;
    height: 50px;
  }

  .product-name {
    font-size: 12px;
  }

  .product-price {
    font-size: 13px;
  }

  .order-footer {
    padding: 10px 12px;
  }

  .order-actions .el-button {
    font-size: 11px;
    padding: 5px 10px;
  }
}

.commented-text {
  color: #909399;
  font-size: 14px;
  margin-left: 8px;
}
</style>
